package cn.net.autocode.platform.file.service;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.core.utils.UserThreadLocalUtils;
import cn.net.autocode.platform.config.SpringProfileConfig;
import com.alibaba.fastjson2.JSONObject;
import cn.net.autocode.dbManager.Dao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;

@Service
public class FileServ {
    private final Dao dao;
    private final SpringProfileConfig springProfileConfig;

    public FileServ(Dao dao, SpringProfileConfig springProfileConfig) {
        this.dao = dao;
        this.springProfileConfig = springProfileConfig;
    }

    @Transactional
    public void delFile(String fileId) throws IOException {
        JSONObject autocodeFile = dao.queryJSON("select * from autocode_file where id=?", fileId);
        String busiId = autocodeFile.getString("busiId");
        String tableName = autocodeFile.getString("tableName");
        String tableColumn = autocodeFile.getString("tableColumn");
        if(StrUtil.isNotBlank(tableColumn)&&StrUtil.isNotBlank(tableName)&& StrUtil.isNotBlank(busiId)){
            try {
                dao.executeUpdate("update "+tableName+" set "+tableColumn+"=? where id=?",null,busiId);
            } catch (Exception e) {
                //throw new RuntimeException(e);
            }
        }
        String storage = autocodeFile.getString("storage");
        if("database".equalsIgnoreCase(storage)){
            dao.delFile(fileId);
        }else{
            String filePath = autocodeFile.getString("filePath");
            if(StrUtil.isNotBlank(filePath)){
                FileHandle.deleteFromDisk(springProfileConfig.getRootDir(), filePath);
            }
        }
    }

    @Transactional
    public JSONObject saveFile(MultipartFile file,String tableName,String tableColumn,String busiId,String attachmentType) throws IOException {
        if(StrUtil.isBlank(tableName)){
            throw new RuntimeException("tableName参数不能为空");
        }

        if(StrUtil.isBlank(busiId)){
            throw new RuntimeException("busiId参数不能为空");
        }

        String fileName = file.getOriginalFilename();
        String fileType = FileHandle.getFileSuffix(fileName).toLowerCase();

        String storage = springProfileConfig.getStorage();
        if("database".equalsIgnoreCase(storage)){
            //存储到数据库
            String fileId = dao.saveFile(file.getBytes(),fileName,fileType);

            //更改附件信息
            JSONObject fj = new JSONObject();
            fj.put("busiId", busiId);
            fj.put("tableName", tableName.toLowerCase().trim());
            if(StrUtil.isNotBlank(tableColumn)){
                fj.put("tableColumn", tableColumn.toLowerCase().trim());
            }
            fj.put("uploadUser", UserThreadLocalUtils.getUserName());
            fj.put("uploadTime", new Date());
            fj.put("attachmentType",attachmentType);//扩展属性  ;
            fj.put("id", fileId);
            fj.put("createTime",new Date());
            fj.put("fileName",fileName);
            fj.put("fileType",fileType);
            dao.updateJSON(fj, "autocode_file");
            return fj;
        }else{
            JSONObject fj = FileHandle.saveToUploadDisk(springProfileConfig.getRootDir(),file);

            fj.put("busiId", busiId);
            fj.put("tableName", tableName.toLowerCase().trim());
            if(StrUtil.isNotBlank(tableColumn)){
                fj.put("tableColumn", tableColumn.toLowerCase().trim());
            }
            fj.put("uploadUser", UserThreadLocalUtils.getUserName());
            fj.put("attachmentType",attachmentType);//扩展属性  ;
            fj.put("id", fj.getString("fileId"));
            fj.put("storage",storage);
            fj.put("createTime", LocalDateTime.now());
            fj.put("uploadTime", LocalDateTime.now());

            dao.createJSON(fj, "autocode_file");
            return fj;
        }


    }

    @Transactional
    public JSONObject updateFile(MultipartFile file,String fileId) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileType = FileHandle.getFileSuffix(fileName).toLowerCase();

        JSONObject autocodeFile = dao.queryJSON("select * from autocode_file where id=?", fileId);
        String storage = autocodeFile.getString("storage");
        if("database".equalsIgnoreCase(storage)){
            dao.updateFile(file.getBytes(),fileName,fileType,fileId);
            //更改存储信息
            JSONObject fj = new JSONObject();
            fj.put("uploadUser", UserThreadLocalUtils.getUserName());
            fj.put("uploadTime", new Date());
            fj.put("id", fileId);
            fj.put("fileName",fileName);
            fj.put("fileType",fileType);
            dao.updateJSON(fj, "autocode_file");
            return fj;
        }else{
            String filePath = autocodeFile.getString("filePath");
            if(StrUtil.isNotBlank(filePath)){
                FileHandle.deleteFromDisk(springProfileConfig.getRootDir(), filePath);
            }
            JSONObject fj = FileHandle.saveToUploadDisk(springProfileConfig.getRootDir(),file);

            fj.put("uploadUser", UserThreadLocalUtils.getUserName());
            fj.put("uploadTime", new Date());
            fj.put("id", fileId);
            fj.put("fileName",fileName);
            fj.put("fileType",fileType);
            dao.updateJSON(fj, "autocode_file");
            return fj;
        }
    }
}
